package com.hddz.acquisition.fragment;

import java.lang.reflect.Field;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.hddz.acquisition.R;

import org.xutils.x;


public abstract class BaseFragment extends Fragment {
	private LayoutInflater inflater;
	private Context context;
	private ViewGroup container;

	private boolean injected = false;


	protected Dialog dialog = null;

	private View rootView;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		context = getActivity().getApplicationContext();
	}




	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
							 Bundle savedInstanceState) {
		if (null == rootView) {
			rootView = x.view().inject(this, inflater, container);

			dialog = new Dialog(getContext(), R.style.progress_dialog);
			dialog.setContentView(R.layout.view_dialog_process);
			dialog.setCancelable(true);
			dialog.getWindow().setBackgroundDrawableResource(
					android.R.color.transparent);
			appandChild(rootView);

			/**
			 * 为了保证一开始加载Fragment的时候判断是否需要加载数据
			 */
			if (getUserVisibleHint()) {
				// 加载数据
			}
		} else {
			/**
			 * 缓存的rootView需要判断是否已经被加过parent，
			 * 如果有parent需要从parent删除，要不然会发生这个rootview已经有parent的错误。
			 */
			ViewGroup parent = (ViewGroup) rootView.getParent();
			if (parent != null) {
				parent.removeView(rootView);
			}
		}
		return rootView;
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		if (!injected) {
			x.view().inject(this, this.getView());
		}
	}


	public void setContentView(int layoutResID) {
		setContentView((ViewGroup) inflater.inflate(layoutResID, container, false));
	}

	public void setContentView(View view) {
		rootView = view;
	}

	public View findViewById(int id) {
		if (rootView != null)
			return rootView.findViewById(id);
		return null;
	}

	@Override
	public void onDetach() {
		super.onDetach();
		try {
			Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
			childFragmentManager.setAccessible(true);
			childFragmentManager.set(this, null);

		} catch (NoSuchFieldException e) {
			throw new RuntimeException(e);
		} catch (IllegalAccessException e) {
			throw new RuntimeException(e);
		}
	}


	@Override
	public void setUserVisibleHint(boolean isVisibleToUser) {
		/**
		 * 判断此Fragment是否正在前台显示
		 * 通过判断就知道是否要进行数据加载了
		 */
		if (isVisibleToUser && isVisible()) {
			// 加载数据
		}
		super.setUserVisibleHint(isVisibleToUser);
	}

	public abstract void appandChild(View view);
}
